export default {
	get,
	postKV,
	postJson
}

function get(options) {
	return request(options, "GET");
}

function postKV(options) {
	optionsConvert(options);
	//初始化 请求头
	if ("header" in options) {
		options.header["content-type"] = "application/x-www-form-urlencoded";
	} else {
		options.header = {
			"content-type": "application/x-www-form-urlencoded"
		};
	}
	return request(options, "POST");
}

function postJson(options) {
	optionsConvert(options);
	//初始化 请求头
	if ("header" in options) {
		options.header["content-type"] = "application/json";
	} else {
		options.header = {
			"content-type": "application/json"
		};
	}
	return request(options, "POST");
}

/**
 * 参数转换 如果没有 loading 相关参数则 添加默认值
 */
function optionsConvert(options){
	if(!("loadTitle" in options)){
		options.loadTitle = "加载中...";
	}
	if(!("showLoading" in options)){
		options.showLoading = true;
	}
	if(!("showError" in options)){
		options.showError = true;
	}
}

/**
 * 输入日志
 * @param {Object} tag 标记
 * @param {Object} content 内容
 */
function log(tag, content) {
	console.debug("网络请求日志=============", tag)
	console.debug(content);
}

/**
 * 处理公共参数
 */
function handleCommonParameters(options) {
	//如果需要添加公共参数
	let data = {
		"version": 1,
		"platform": "uniapp",
		...options.data
	};
	//如果需要添加 请求头
	let header = {
		"token": "xxx",
		...options.header
	}
	let url = "https://www.wanandroid.com/" + options.url;
	return {
		"url": url,
		"data": data,
		"header": header,
	}

}


/**
 * 网络请求核心方法
 */
function request(options, method) {
	//添加公共参数
	const params = handleCommonParameters(options);
	log("request", params);
	if (options.showLoading) {
		uni.showLoading({
			title: options.loadTitle
		})
	}
	return new Promise(function(resolve, reject) {
		uni.request({
			url: params.url,
			data: params.data,
			method: method,
			header: params.header,
			success: (response) => {
				log("response", response);
				let statusCode = response.statusCode;
				//判断网络状态码
				if (statusCode === 200) {
					let httpData = response.data;
					//接口业务码
					if (httpData.errorCode === 0) {
						if (options.showLoading) {
							uni.hideLoading();
						}
						resolve(httpData.data);
					} else {
						//接口业务码错误
						if (options.showError) {
							uni.showToast({
								icon: "none",
								title: httpData.errorMsg
							})
						}
						reject({
							code: httpData.errorCode,
							msg: httpData.errorMsg
						});
					}
				} else {
					//网络状态码错误
					if (options.showError) {
						uni.showToast({
							icon: "none",
							title: response.errorMsg
						})
					}
					reject({
						code: statusCode,
						msg: response.errMsg
					});
				}
			},
			fail: (error) => {
				log("error", error);
				let code = -1;
				let message = error;
				if (options.showError) {
					uni.showToast({
						icon: "none",
						title: message
					})
				}
				reject({
					code: code,
					msg: message
				});
			}
		})
	});
}


